﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace TransformerSystem.UI.Behaviors
{
    public class ViewBehavior : Behavior<FrameworkElement>
    {
        private Window Root
        { 
            get
            { 
                var window = Window.GetWindow(AssociatedObject);
                return window;
            }
        }
        private IViewAware Aware
        {
            get
            { 
                return AssociatedObject.DataContext as IViewAware;
            }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Initialized += AssociatedObject_Initialized;
        }

        private void AssociatedObject_Initialized(object sender, EventArgs e)
        {
            if (Aware == null) return;
            Aware.WindowCloase += Aware_WindowCloase;
        }

        private void Aware_WindowCloase()
        { 
            Root?.Close();
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.Initialized += AssociatedObject_Initialized;
        }
    }
}
